<template>
  <div class="generate-backtest">
    <!-- 计算状态显示 -->
    <div v-if="isCalculating" class="calculating-section">
      <div class="section-header">
        <h3>🤖 模型计算中</h3>
        <div class="calculating-status">
          <div class="status-badge calculating">
            <span class="status-icon">⚡</span>
            <span>正在计算...</span>
          </div>
        </div>
      </div>
      
      <div class="calculating-info">
        <div class="spinner-container">
          <div class="spinner"></div>
        </div>
        <div class="progress-info">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: calculationProgress + '%' }"></div>
          </div>
          <div class="progress-text">{{ calculationProgress }}%</div>
        </div>
        <div class="calculating-steps">
          <div class="step" :class="{ active: calculationProgress >= 20 }">
            <span class="step-icon">📊</span>
            <span class="step-text">数据预处理</span>
          </div>
          <div class="step" :class="{ active: calculationProgress >= 40 }">
            <span class="step-icon">🔍</span>
            <span class="step-text">特征工程</span>
          </div>
          <div class="step" :class="{ active: calculationProgress >= 60 }">
            <span class="step-icon">🤖</span>
            <span class="step-text">模型训练</span>
          </div>
          <div class="step" :class="{ active: calculationProgress >= 80 }">
            <span class="step-icon">📈</span>
            <span class="step-text">回测验证</span>
          </div>
          <div class="step" :class="{ active: calculationProgress >= 100 }">
            <span class="step-icon">✅</span>
            <span class="step-text">结果生成</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 实盘跟踪状态 -->
    <div v-if="isLiveTrading" class="live-trading-section">
      <div class="section-header">
        <h3>📊 实盘跟踪状态</h3>
        <div class="live-status">
          <div class="status-indicator active">
            <span class="status-dot"></span>
            <span class="status-text">实盘运行中</span>
          </div>
          <div class="live-info">
            <div class="info-item">
              <span class="label">开始日期:</span>
              <span class="value">{{ liveStartDate }}</span>
            </div>
            <div class="info-item">
              <span class="label">最后更新:</span>
              <span class="value">{{ lastUpdateTime }}</span>
            </div>
          </div>
          <div class="live-actions">
            <button @click="stopLiveTrading" class="btn-danger">
              🛑 停止实盘
            </button>
            <button @click="refreshLiveData" class="btn-info">
              🔄 刷新数据
            </button>
          </div>
        </div>
      </div>
    </div>

         <!-- 模型运行状态 -->
     <div v-if="isLiveTrading" class="model-status-section">
       <div class="section-header">
         <h3>🤖 模型运行状态</h3>
         <div class="model-status">
           <div class="status-badge running">
             <span class="status-icon">⚡</span>
             <span>模型运行中</span>
           </div>
         </div>
       </div>
       
       <div class="model-info">
         <div class="info-grid">
           <div class="info-card">
             <div class="card-title">📊 当前资产</div>
             <div class="card-value">${{ formatNumber(currentPortfolio.totalValue) }}</div>
             <div class="card-subtitle">实盘跟踪期间</div>
           </div>
           <div class="info-card">
             <div class="card-title">📈 累计收益</div>
             <div class="card-value" :class="getReturnClass(currentPortfolio.totalReturn)">
               {{ formatPercentage(currentPortfolio.totalReturn) }}
             </div>
             <div class="card-subtitle">相对实盘开始</div>
           </div>
           <div class="info-card">
             <div class="card-title">🔄 今日收益</div>
             <div class="card-value" :class="getReturnClass(currentPortfolio.dailyReturn)">
               {{ formatPercentage(currentPortfolio.dailyReturn) }}
             </div>
             <div class="card-subtitle">当日表现</div>
           </div>
         </div>
       </div>
     </div>

           <!-- 今日模型建议 -->
      <div v-if="isLiveTrading" class="today-advice-section">
        <div class="section-header">
          <h3>💡 今日模型建议</h3>
          <div class="advice-date">{{ todayDate }}</div>
        </div>
        
        <div class="advice-content">
          <div class="model-explanation">
            <div class="explanation-header">
              <span class="icon">📋</span>
              <span>基于模型测试期间（最后一个月）的加仓建议点位</span>
            </div>
            <div class="explanation-text">
              模型分析今日股票数据，结合历史表现，给出量化操作建议
            </div>
          </div>
          
          <!-- 模型二持仓管理参数 -->
          <div v-if="backtestResults && backtestResults.optimizationResult" class="model2-params-section">
            <h4>🔧 模型二持仓管理参数</h4>
            <div class="params-grid">
              <div class="param-card">
                <div class="param-title">优化股票池</div>
                <div class="param-value">{{ backtestResults.optimizationResult.summary.optimized_count }} 只</div>
                <div class="param-desc">从 {{ backtestResults.optimizationResult.summary.original_count }} 只中筛选</div>
              </div>
              <div class="param-card">
                <div class="param-title">筛选比例</div>
                <div class="param-value">{{ formatPercentage(backtestResults.optimizationResult.summary.filtering_ratio / 100) }}</div>
                <div class="param-desc">保留高质量股票</div>
              </div>
              <div class="param-card">
                <div class="param-title">平均重要性</div>
                <div class="param-value">{{ getAverageImportance() }}</div>
                <div class="param-desc">特征重要性评分</div>
              </div>
              <div class="param-card">
                <div class="param-title">相关性控制</div>
                <div class="param-value">{{ getCorrelationGroupsCount() }} 组</div>
                <div class="param-desc">避免重复信息</div>
              </div>
            </div>
          </div>
          
          <!-- 模型测试结果展示区域 -->
          <div v-if="backtestResults && (backtestResults.backtest_results || backtestResults.recommendations)" class="model-test-results-section">
            <h4>🤖 模型测试结果</h4>
            
            <!-- 回测结果 -->
            <div v-if="backtestResults.backtest_results" class="backtest-results">
              <h5>📊 回测表现</h5>
              <div class="results-grid">
                <div class="result-card">
                  <div class="result-title">初始资金</div>
                  <div class="result-value">${{ formatNumber(backtestResults.backtest_results.initial_capital || 0) }}</div>
                </div>
                <div class="result-card">
                  <div class="result-title">最终资金</div>
                  <div class="result-value">${{ formatNumber(backtestResults.backtest_results.final_capital || 0) }}</div>
                </div>
                <div class="result-card">
                  <div class="result-title">总收益率</div>
                  <div class="result-value" :class="getReturnClass(backtestResults.backtest_results.total_return || 0)">
                    {{ formatPercentage(backtestResults.backtest_results.total_return || 0) }}
                  </div>
                </div>
                <div class="result-card">
                  <div class="result-title">最大回撤</div>
                  <div class="result-value" :class="getReturnClass(-(backtestResults.backtest_results.max_drawdown || 0))">
                    {{ formatPercentage(backtestResults.backtest_results.max_drawdown || 0) }}
                  </div>
                </div>
                <div class="result-card">
                  <div class="result-title">夏普比率</div>
                  <div class="result-value">{{ (backtestResults.backtest_results.sharpe_ratio || 0).toFixed(3) }}</div>
                </div>
                <div class="result-card">
                  <div class="result-title">胜率</div>
                  <div class="result-value">{{ formatPercentage(backtestResults.backtest_results.win_rate || 0) }}</div>
                </div>
              </div>
            </div>
            
            <!-- 投资建议 -->
            <div v-if="backtestResults.recommendations" class="investment-recommendations">
              <h5>💡 投资组合建议</h5>
              <div v-if="backtestResults.recommendations.positions" class="recommendations-grid">
                <div 
                  v-for="(position, symbol) in backtestResults.recommendations.positions" 
                  :key="symbol"
                  class="recommendation-card"
                >
                  <div class="rec-symbol">{{ symbol }}</div>
                  <div class="rec-weight">{{ formatPercentage(position.weight || 0) }}</div>
                  <div class="rec-action">{{ position.action || '持有' }}</div>
                </div>
              </div>
            </div>
            
            <!-- 模型性能 -->
            <div v-if="backtestResults.model1_results || backtestResults.model2_results" class="model-performance">
              <h5>🎯 模型性能</h5>
              <div class="performance-grid">
                <div v-if="backtestResults.model1_results" class="performance-card">
                  <div class="perf-title">多因子模型</div>
                  <div class="perf-details">
                    <div v-for="(result, target) in backtestResults.model1_results" :key="target" class="perf-item">
                      <span class="perf-target">{{ target }}</span>
                      <span class="perf-accuracy">{{ (result.accuracy || 0).toFixed(3) }}</span>
                    </div>
                  </div>
                </div>
                <div v-if="backtestResults.model2_results" class="performance-card">
                  <div class="perf-title">个股模型</div>
                  <div class="perf-details">
                    <div v-for="(result, symbol) in backtestResults.model2_results" :key="symbol" class="perf-item">
                      <span class="perf-target">{{ symbol }}</span>
                      <span class="perf-accuracy">{{ (result.accuracy || 0).toFixed(3) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 市场数据摘要 -->
            <div v-if="backtestResults.market_data_summary" class="market-summary">
              <h5>📈 数据摘要</h5>
              <div class="summary-grid">
                <div class="summary-item">
                  <span class="summary-label">股票数量:</span>
                  <span class="summary-value">{{ backtestResults.market_data_summary.total_stocks }}</span>
                </div>
                <div class="summary-item">
                  <span class="summary-label">数据点数:</span>
                  <span class="summary-value">{{ backtestResults.market_data_summary.data_points }}</span>
                </div>
                <div class="summary-item">
                  <span class="summary-label">日期范围:</span>
                  <span class="summary-value">{{ backtestResults.market_data_summary.date_range?.start }} 至 {{ backtestResults.market_data_summary.date_range?.end }}</span>
                </div>
              </div>
            </div>
            
            <!-- 优化参数 -->
            <div v-if="backtestResults.optimized_params" class="optimized-params">
              <h5>🔧 优化参数</h5>
              <div class="params-grid">
                <div 
                  v-for="(value, key) in backtestResults.optimized_params" 
                  :key="key"
                  class="param-card"
                >
                  <div class="param-title">{{ formatParamName(key) }}</div>
                  <div class="param-value">{{ formatParamValue(value) }}</div>
                </div>
              </div>
            </div>
            
            <!-- 模型配置 -->
            <div v-if="backtestResults.model_config" class="model-config">
              <h5>⚙️ 模型配置</h5>
              <div class="config-grid">
                <div 
                  v-for="(value, key) in backtestResults.model_config" 
                  :key="key"
                  class="config-item"
                >
                  <span class="config-label">{{ formatParamName(key) }}:</span>
                  <span class="config-value">{{ formatParamValue(value) }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="today-positions">
            <div class="positions-header">
              <span>股票代码</span>
              <span>当前价格</span>
              <span>今日涨跌</span>
              <span>模型评分</span>
              <span>优化评分</span>
              <span>建议操作</span>
              <span>建议理由</span>
            </div>
            <div 
              v-for="position in currentPortfolio.positions" 
              :key="position.symbol"
              class="position-row"
            >
              <span class="symbol">{{ position.symbol }}</span>
              <span class="price">${{ formatNumber(position.currentPrice) }}</span>
              <span class="change" :class="getReturnClass(position.dailyChange)">
                {{ formatPercentage(position.dailyChange) }}
              </span>
              <span class="model-score" :class="getScoreClass(position.modelScore)">
                {{ formatScore(position.modelScore) }}
              </span>
              <span class="optimization-score" :class="getOptimizationScoreClass(position.optimizationScore)">
                {{ formatScore(position.optimizationScore) }}
              </span>
              <span class="action" :class="getActionClass(position.action)">
                {{ getActionText(position.action) }}
              </span>
              <span class="reason">{{ getActionReason(position) }}</span>
            </div>
          </div>
        </div>
      </div>

    <!-- 持仓历史 -->
    <div v-if="isLiveTrading" class="history-section">
      <div class="section-header">
        <h3>📈 持仓历史</h3>
        <div class="history-controls">
          <select v-model="selectedHistoryPeriod" class="history-select">
            <option value="7">最近7天</option>
            <option value="30">最近30天</option>
            <option value="90">最近90天</option>
          </select>
        </div>
      </div>
      
      <div class="history-content">
        <div 
          v-for="day in portfolioHistory" 
          :key="day.date"
          class="history-day"
        >
          <div class="day-header">
            <span class="day-date">{{ formatDate(day.date) }}</span>
            <span class="day-value">${{ formatNumber(day.totalValue) }}</span>
            <span class="day-return" :class="getReturnClass(day.dailyReturn)">
              {{ formatPercentage(day.dailyReturn) }}
            </span>
          </div>
          <div class="day-actions">
            <div 
              v-for="action in day.actions" 
              :key="action.id"
              class="action-item"
              :class="action.type"
            >
              <span class="action-symbol">{{ action.symbol }}</span>
              <span class="action-type">{{ action.action }}</span>
              <span class="action-details">{{ action.details }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作控制 -->
    <div class="control-section" v-if="hasBacktestResults">
      <div class="button-group">
        <button 
          @click="startLiveTrading" 
          :disabled="!canStartLiveTrading"
          class="btn-success"
        >
          📈 开始实盘
        </button>
        <button 
          @click="clearOldData" 
          class="btn-secondary"
        >
          🗑️ 清空结果
        </button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'GenerateBacktest',
  props: {
    selectedStocks: {
      type: Array,
      default: () => []
    },
    initialCapital: {
      type: Number,
      default: 100000
    },
    backtestResults: {
      type: Object,
      default: null
    },
    isCalculating: {
      type: Boolean,
      default: false
    },
    calculationProgress: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isLiveTrading: false,
      liveStartDate: '',
      lastUpdateTime: '',
      currentPortfolio: {
        totalValue: 0,
        dailyReturn: 0,
        totalReturn: 0,
        initialValue: 0, // 实盘开始时的初始资金
        positions: []
      },
      portfolioHistory: [],
      selectedHistoryPeriod: 30,
      tradingLogs: [],
      logCounter: 0,
      liveTradingInterval: null
    }
  },
  computed: {
    canStartLiveTrading() {
      return this.selectedStocks.length > 0 && this.backtestResults && !this.isLiveTrading
    },
    hasBacktestResults() {
      return this.backtestResults !== null
    },
    todayDate() {
      return new Date().toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      })
    }
  },
  watch: {
    backtestResults: {
      handler(newResults) {
        if (newResults) {
          console.log('🔄 GenerateBacktest收到新的模型测试结果:', newResults)
          this.updateDisplayWithResults(newResults)
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    updateDisplayWithResults(results) {
      // 更新显示逻辑，处理新的模型测试结果
      console.log('📊 更新显示结果:', results)
      console.log('📊 回测结果:', results.backtest_results)
      console.log('📊 优化结果:', results.optimizationResult)
      
      // 如果有回测结果，显示相关数据
      if (results.backtest_results) {
        const backtest = results.backtest_results
        console.log('📈 回测结果:', backtest)
      }
      
      // 如果有投资建议，显示相关数据
      if (results.recommendations) {
        const recommendations = results.recommendations
        console.log('💡 投资建议:', recommendations)
      }
      
      // 如果有模型结果，显示相关数据
      if (results.model1_results) {
        console.log('🤖 模型1结果:', results.model1_results)
      }
      
      if (results.model2_results) {
        console.log('🤖 模型2结果:', results.model2_results)
      }
    },
    async startLiveTrading() {
      if (!this.canStartLiveTrading) return
      
      this.isLiveTrading = true
      this.liveStartDate = new Date().toLocaleDateString()
      
      // 清除旧的建议和日志
      this.clearOldData()
      
      // 基于回测结果初始化实盘持仓
      this.initializeLivePortfolio()
      
      // 开始定时更新
      this.startLiveUpdates()
      
      // 记录开始日志
      this.addTradingLog('SYSTEM', 'START', '开始实盘跟踪')
      
      // 触发父组件事件
      this.$emit('live-trading-started')
      
      console.log('开始实盘跟踪')
    },
    
    stopLiveTrading() {
      this.isLiveTrading = false
      
      // 停止定时更新
      if (this.liveTradingInterval) {
        clearInterval(this.liveTradingInterval)
        this.liveTradingInterval = null
      }
      
      // 记录停止日志
      this.addTradingLog('SYSTEM', 'STOP', '停止实盘跟踪')
      
      // 触发父组件事件
      this.$emit('live-trading-stopped')
      
      console.log('停止实盘跟踪')
    },
    
    clearOldData() {
      // 清除实盘跟踪数据
      this.tradingLogs = []
      this.logCounter = 0
      this.portfolioHistory = []
      this.currentPortfolio = {
        totalValue: 0,
        dailyReturn: 0,
        totalReturn: 0,
        initialValue: 0,
        positions: []
      }
      console.log('已清除实盘跟踪数据')
      
      // 触发父组件事件
      this.$emit('old-data-cleared')
    },
    
    initializeLivePortfolio() {
      // 基于回测结果初始化持仓，从实盘开始时的资金计算
      const positionValue = this.initialCapital / this.selectedStocks.length
      
      this.currentPortfolio = {
        totalValue: this.initialCapital,
        dailyReturn: 0,
        totalReturn: 0,
        initialValue: this.initialCapital, // 记录实盘开始时的初始资金
                 positions: this.selectedStocks.map(stock => ({
           symbol: stock.replace('.US', ''),
           quantity: Math.floor(positionValue / 100),
           currentPrice: 100 + Math.random() * 50,
           value: positionValue,
           dailyChange: (Math.random() - 0.5) * 0.1,
           action: 'HOLD',
           modelScore: 0, // 模型评分 (-1 到 1)
           actionReason: '', // 操作建议理由
           optimizationScore: this.getOptimizationScore(stock) // 优化评分
         }))
      }
      
      this.updateLastUpdateTime()
    },
    
    startLiveUpdates() {
      // 每分钟更新一次数据
      this.liveTradingInterval = setInterval(() => {
        this.updateLiveData()
      }, 60000) // 60秒
      
      // 立即执行一次更新
      this.updateLiveData()
    },
    
    updateLiveData() {
      // 模拟实时数据更新
      this.currentPortfolio.positions.forEach(position => {
        // 更新价格
        const priceChange = (Math.random() - 0.5) * 0.02
        position.currentPrice *= (1 + priceChange)
        position.currentPrice = Math.max(position.currentPrice, 1)
        
        // 更新持仓价值
        position.value = position.quantity * position.currentPrice
        
        // 更新日涨跌幅
        position.dailyChange = (Math.random() - 0.5) * 0.1
        
        // 基于模型生成操作建议
        this.generateModelAdvice(position)
      })
      
      // 更新总资产
      this.currentPortfolio.totalValue = this.currentPortfolio.positions.reduce(
        (sum, pos) => sum + pos.value, 0
      )
      
      // 更新收益率 - 基于实盘开始时的资金计算
      this.currentPortfolio.totalReturn = (this.currentPortfolio.totalValue - this.currentPortfolio.initialValue) / this.currentPortfolio.initialValue
      
      this.updateLastUpdateTime()
      
      // 检查是否需要记录交易
      this.checkAndRecordTrades()
      
      // 更新持仓历史
      this.updatePortfolioHistory()
      
      // 触发父组件事件
      this.$emit('data-updated', this.currentPortfolio)
    },
    
         generateModelAdvice(position) {
       // 基于模型测试期间（最后一个月）的加仓建议点位生成操作建议
       if (this.backtestResults && this.backtestResults.modelPredictions) {
         // 模拟模型评分 (-1 到 1)
         const baseScore = this.backtestResults.modelPredictions[position.symbol] || 0
         const currentTrend = position.dailyChange
         const volatility = Math.random() * 0.1
         
         // 获取优化评分
         const optimizationScore = position.optimizationScore || 0.5
         
         // 综合评分：基础模型预测 + 当前趋势 + 波动性调整 + 优化评分
         position.modelScore = Math.max(-1, Math.min(1, 
           baseScore * 0.4 + 
           currentTrend * 0.3 + 
           volatility * 0.2 + 
           optimizationScore * 0.1
         ))
         
         // 根据评分确定操作建议
         if (position.modelScore > 0.3) {
           position.action = 'BUY'
           position.actionReason = `模型评分${(position.modelScore * 100).toFixed(1)}分，优化评分${(optimizationScore * 100).toFixed(1)}分，建议加仓`
         } else if (position.modelScore < -0.3) {
           position.action = 'SELL'
           position.actionReason = `模型评分${(position.modelScore * 100).toFixed(1)}分，优化评分${(optimizationScore * 100).toFixed(1)}分，建议减仓`
         } else {
           position.action = 'HOLD'
           position.actionReason = `模型评分${(position.modelScore * 100).toFixed(1)}分，优化评分${(optimizationScore * 100).toFixed(1)}分，建议持有`
         }
       } else {
         // 模拟模型建议（基于价格趋势和技术指标）
         const trendScore = position.dailyChange * 2 // 趋势权重
         const momentumScore = (Math.random() - 0.5) * 0.5 // 动量指标
         const volumeScore = (Math.random() - 0.5) * 0.3 // 成交量指标
         const optimizationScore = position.optimizationScore || 0.5
         
         position.modelScore = Math.max(-1, Math.min(1, 
           trendScore * 0.4 + 
           momentumScore * 0.3 + 
           volumeScore * 0.2 + 
           optimizationScore * 0.1
         ))
         
         if (position.modelScore > 0.2) {
           position.action = 'BUY'
           position.actionReason = `技术指标向好，评分${(position.modelScore * 100).toFixed(1)}分，优化评分${(optimizationScore * 100).toFixed(1)}分`
         } else if (position.modelScore < -0.2) {
           position.action = 'SELL'
           position.actionReason = `技术指标转弱，评分${(position.modelScore * 100).toFixed(1)}分，优化评分${(optimizationScore * 100).toFixed(1)}分`
         } else {
           position.action = 'HOLD'
           position.actionReason = `技术指标中性，评分${(position.modelScore * 100).toFixed(1)}分，优化评分${(optimizationScore * 100).toFixed(1)}分`
         }
       }
     },
    
    checkAndRecordTrades() {
      this.currentPortfolio.positions.forEach(position => {
        if (position.action !== 'HOLD') {
          this.addTradingLog(
            position.symbol,
            position.action,
            `价格: $${position.currentPrice.toFixed(2)}, 涨跌: ${(position.dailyChange * 100).toFixed(2)}%`
          )
        }
      })
    },
    
    updatePortfolioHistory() {
      const today = new Date().toISOString().split('T')[0]
      const todayActions = this.tradingLogs.filter(log => 
        log.timestamp.toISOString().split('T')[0] === today
      )
      
      const historyEntry = {
        date: today,
        totalValue: this.currentPortfolio.totalValue,
        dailyReturn: this.currentPortfolio.dailyReturn,
        actions: todayActions.map(log => ({
          id: log.id,
          symbol: log.symbol,
          action: log.action,
          details: log.details,
          type: log.type
        }))
      }
      
      // 更新或添加今日记录
      const existingIndex = this.portfolioHistory.findIndex(entry => entry.date === today)
      if (existingIndex >= 0) {
        this.portfolioHistory[existingIndex] = historyEntry
      } else {
        this.portfolioHistory.unshift(historyEntry)
      }
      
      // 限制历史记录数量
      if (this.portfolioHistory.length > this.selectedHistoryPeriod) {
        this.portfolioHistory = this.portfolioHistory.slice(0, this.selectedHistoryPeriod)
      }
    },
    
    addTradingLog(symbol, action, details) {
      this.logCounter++
      this.tradingLogs.unshift({
        id: this.logCounter,
        timestamp: new Date(),
        symbol,
        action,
        details,
        type: action === 'BUY' ? 'buy' : action === 'SELL' ? 'sell' : 'system'
      })
      
      // 限制日志数量
      if (this.tradingLogs.length > 100) {
        this.tradingLogs = this.tradingLogs.slice(0, 100)
      }
      
      // 触发父组件事件
      this.$emit('log-added', this.tradingLogs[0])
    },
    
    refreshLiveData() {
      // 只更新当前价格和持仓价值，不重置累计收益
      this.currentPortfolio.positions.forEach(position => {
        // 更新价格
        const priceChange = (Math.random() - 0.5) * 0.02
        position.currentPrice *= (1 + priceChange)
        position.currentPrice = Math.max(position.currentPrice, 1)
        
        // 更新持仓价值
        position.value = position.quantity * position.currentPrice
        
        // 更新日涨跌幅
        position.dailyChange = (Math.random() - 0.5) * 0.1
        
        // 基于模型生成操作建议
        this.generateModelAdvice(position)
      })
      
      // 更新总资产
      this.currentPortfolio.totalValue = this.currentPortfolio.positions.reduce(
        (sum, pos) => sum + pos.value, 0
      )
      
      // 更新收益率 - 基于实盘开始时的资金计算
      this.currentPortfolio.totalReturn = (this.currentPortfolio.totalValue - this.currentPortfolio.initialValue) / this.currentPortfolio.initialValue
      
      this.updateLastUpdateTime()
      
      // 检查是否需要记录交易
      this.checkAndRecordTrades()
      
      // 更新持仓历史
      this.updatePortfolioHistory()
      
      this.addTradingLog('SYSTEM', 'REFRESH', '手动刷新数据')
    },
    
    updateLastUpdateTime() {
      this.lastUpdateTime = new Date().toLocaleString()
    },
    
    formatPercentage(value) {
      return `${(value * 100).toFixed(2)}%`
    },
    
    formatNumber(value) {
      return value.toFixed(2)
    },
    
    formatDate(dateString) {
      return new Date(dateString).toLocaleDateString('zh-CN', {
        month: 'short',
        day: 'numeric'
      })
    },
    
    getReturnClass(value) {
      return value >= 0 ? 'positive' : 'negative'
    },
    
    getActionClass(action) {
      switch (action) {
        case 'BUY': return 'buy'
        case 'SELL': return 'sell'
        default: return 'hold'
      }
    },
    
         getActionText(action) {
       switch (action) {
         case 'BUY': return '加仓'
         case 'SELL': return '减仓'
         default: return '持有'
       }
     },
     
     formatScore(score) {
       return `${(score * 100).toFixed(1)}`
     },
     
     getScoreClass(score) {
       if (score > 0.3) return 'score-high'
       if (score < -0.3) return 'score-low'
       return 'score-medium'
     },
     
           getActionReason(position) {
        return position.actionReason || '模型分析中...'
      },
      
      getOptimizationScore(stock) {
        // 从回测结果中获取优化评分
        if (this.backtestResults && this.backtestResults.optimizationResult) {
          const optimizedStocks = this.backtestResults.optimizationResult.optimized_stocks_details
          if (optimizedStocks && optimizedStocks[stock]) {
            return optimizedStocks[stock].avg_importance
          }
        }
        return 0.5 // 默认评分
      },
      
      getOptimizationScoreClass(score) {
        if (score > 0.15) return 'score-high'
        if (score < 0.05) return 'score-low'
        return 'score-medium'
      },
      
      getAverageImportance() {
        if (this.backtestResults && this.backtestResults.optimizationResult) {
          const optimizedStocks = this.backtestResults.optimizationResult.optimized_stocks_details
          if (optimizedStocks) {
            const scores = Object.values(optimizedStocks).map(stock => stock.avg_importance)
            const avg = scores.reduce((sum, score) => sum + score, 0) / scores.length
            return this.formatNumber(avg)
          }
        }
        return '0.00'
      },
      
      getCorrelationGroupsCount() {
        if (this.backtestResults && this.backtestResults.optimizationResult) {
          return this.backtestResults.optimizationResult.high_correlation_groups?.length || 0
        }
        return 0
      },

      formatParamName(key) {
        // 将键名转换为更友好的名称
        switch (key) {
          case 'optimized_count': return '优化股票数量'
          case 'filtering_ratio': return '筛选比例'
          case 'avg_importance': return '平均重要性'
          case 'correlation_groups': return '相关性控制'
          case 'total_stocks': return '总股票数量'
          case 'data_points': return '数据点数'
          case 'date_range': return '日期范围'
          case 'initial_capital': return '初始资金'
          case 'final_capital': return '最终资金'
          case 'total_return': return '总收益率'
          case 'max_drawdown': return '最大回撤'
          case 'sharpe_ratio': return '夏普比率'
          case 'win_rate': return '胜率'
          case 'optimized_stocks_details': return '优化股票详情'
          case 'high_correlation_groups': return '高相关性组'
          case 'model_config': return '模型配置'
          case 'optimized_params': return '优化参数'
          default: return key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
        }
      },

      formatParamValue(value) {
        if (typeof value === 'number') {
          if (value >= 0 && value <= 1) {
            return (value * 100).toFixed(2) + '%'
          } else if (value > 1 && value < 100) {
            return value.toFixed(2)
          } else {
            return value.toFixed(0)
          }
        } else if (typeof value === 'string') {
          return value
        } else if (typeof value === 'object' && value !== null) {
          if (Array.isArray(value)) {
            return value.join(', ')
          } else {
            return JSON.stringify(value)
          }
        } else {
          return String(value)
        }
      }
  },
  
  beforeUnmount() {
    // 组件销毁前清理定时器
    if (this.liveTradingInterval) {
      clearInterval(this.liveTradingInterval)
    }
  }
}
</script>

<style scoped>
.generate-backtest {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 通用样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

/* 按钮样式 */
.button-group {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.btn-success, .btn-secondary, .btn-danger, .btn-info, .btn-small {
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn-success:hover:not(:disabled) {
  background: #218838;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background: #5a6268;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: #c82333;
}

.btn-info {
  background: #17a2b8;
  color: white;
}

.btn-info:hover:not(:disabled) {
  background: #138496;
}

.btn-small {
  padding: 6px 12px;
  font-size: 12px;
  background: #f8f9fa;
  color: #666;
  border: 1px solid #ddd;
}

.btn-small:hover {
  background: #e9ecef;
}

.btn-success:disabled, .btn-secondary:disabled, .btn-danger:disabled, .btn-info:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 计算状态 */
.calculating-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.calculating-status {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-badge.calculating {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-icon {
  font-size: 16px;
}

.calculating-info {
  margin-top: 20px;
  text-align: center;
}

.spinner-container {
  margin-bottom: 20px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.progress-info {
  margin-bottom: 24px;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 14px;
  font-weight: 600;
  color: #667eea;
}

.calculating-steps {
  display: flex;
  justify-content: space-between;
  gap: 8px;
  margin-top: 20px;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  opacity: 0.3;
  transition: all 0.3s ease;
}

.step.active {
  opacity: 1;
}

.step-icon {
  font-size: 20px;
}

.step-text {
  font-size: 12px;
  color: #666;
  text-align: center;
  white-space: nowrap;
}

/* 实盘跟踪状态 */
.live-trading-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #28a745;
}

.live-status {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #28a745;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

.status-text {
  font-weight: 600;
  color: #28a745;
}

.live-info {
  display: flex;
  gap: 20px;
}

.info-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.info-item .label {
  font-size: 12px;
  color: #666;
}

.info-item .value {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.live-actions {
  display: flex;
  gap: 8px;
}

.live-actions button {
  flex: 1;
  padding: 8px 12px;
  font-size: 12px;
}

 /* 模型运行状态 */
 .model-status-section {
   background: white;
   border-radius: 8px;
   padding: 20px;
   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
   border-left: 4px solid #17a2b8;
 }

 .model-status {
   display: flex;
   align-items: center;
 }

 .status-badge {
   display: flex;
   align-items: center;
   gap: 6px;
   padding: 6px 12px;
   border-radius: 20px;
   font-size: 12px;
   font-weight: 600;
 }

 .status-badge.running {
   background: rgba(23, 162, 184, 0.1);
   color: #17a2b8;
 }

 .status-icon {
   font-size: 14px;
 }

 .model-info {
   margin-top: 16px;
 }

 .info-grid {
   display: grid;
   grid-template-columns: repeat(3, 1fr);
   gap: 16px;
 }

 .info-card {
   text-align: center;
   padding: 16px;
   background: #f8f9fa;
   border-radius: 8px;
   border: 1px solid #e9ecef;
 }

 .card-title {
   font-size: 12px;
   color: #666;
   margin-bottom: 8px;
 }

 .card-value {
   font-size: 20px;
   font-weight: 700;
   margin-bottom: 4px;
 }

 .card-subtitle {
   font-size: 10px;
   color: #999;
 }

 /* 今日模型建议 */
 .today-advice-section {
   background: white;
   border-radius: 8px;
   padding: 20px;
   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
 }

 .advice-date {
   font-size: 14px;
   color: #666;
   font-weight: 500;
 }

 .model-explanation {
   background: #f8f9fa;
   border-radius: 6px;
   padding: 12px;
   margin-bottom: 16px;
   border-left: 3px solid #17a2b8;
 }

 .explanation-header {
   display: flex;
   align-items: center;
   gap: 8px;
   font-weight: 600;
   color: #333;
   margin-bottom: 4px;
 }

 .explanation-header .icon {
   font-size: 16px;
 }

 .explanation-text {
   font-size: 12px;
   color: #666;
   line-height: 1.4;
 }

.advice-summary {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.summary-item {
  text-align: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.summary-item .label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.summary-item .value {
  display: block;
  font-size: 16px;
  font-weight: 600;
}

.today-positions {
  border: 1px solid #eee;
  border-radius: 6px;
  overflow: hidden;
}

   .positions-header {
    display: grid;
    grid-template-columns: 1.5fr 1fr 1fr 1fr 1fr 1fr 2fr;
    background: #f8f9fa;
    padding: 12px 16px;
    font-weight: 600;
    color: #333;
    font-size: 14px;
  }

  .position-row {
    display: grid;
    grid-template-columns: 1.5fr 1fr 1fr 1fr 1fr 1fr 2fr;
    padding: 12px 16px;
    border-bottom: 1px solid #eee;
    font-size: 14px;
    align-items: center;
  }

.position-row:last-child {
  border-bottom: none;
}

.position-row:hover {
  background: #f8f9fa;
}

.symbol {
  font-weight: 600;
  color: #333;
}

.price, .value, .change, .action {
  text-align: right;
}

.action.buy {
  color: #28a745;
  font-weight: 600;
}

.action.sell {
  color: #dc3545;
  font-weight: 600;
}

 .action.hold {
   color: #6c757d;
 }

 .model-score {
   font-weight: 600;
   text-align: center;
 }

 .model-score.score-high {
   color: #28a745;
 }

 .model-score.score-medium {
   color: #6c757d;
 }

 .model-score.score-low {
   color: #dc3545;
 }

   .reason {
    font-size: 12px;
    color: #666;
    line-height: 1.3;
  }

  .optimization-score {
    font-weight: 600;
    text-align: center;
  }

  .optimization-score.score-high {
    color: #28a745;
  }

  .optimization-score.score-medium {
    color: #6c757d;
  }

  .optimization-score.score-low {
    color: #dc3545;
  }

  /* 模型二参数部分样式 */
  .model2-params-section {
    margin-bottom: 20px;
  }

  .model2-params-section h4 {
    margin: 0 0 16px 0;
    color: #333;
    font-size: 16px;
    font-weight: 600;
  }

  .params-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
  }

  .param-card {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 16px;
    text-align: center;
  }

  .param-title {
    font-size: 12px;
    color: #666;
    margin-bottom: 8px;
    font-weight: 500;
  }

  .param-value {
    font-size: 18px;
    font-weight: 700;
    color: #333;
    margin-bottom: 4px;
  }

  .param-desc {
    font-size: 10px;
    color: #999;
    line-height: 1.2;
  }

/* 模型测试结果展示区域 */
.model-test-results-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #17a2b8;
  margin-top: 20px;
  margin-bottom: 20px;
}

.model-test-results-section h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.backtest-results h5, .investment-recommendations h5, .model-performance h5, .market-summary h5, .optimized-params h5, .model-config h5 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.results-grid, .recommendations-grid, .performance-grid, .summary-grid, .params-grid, .config-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.result-card, .recommendation-card, .performance-card, .param-card, .config-item {
  background: #e9ecef;
  border-radius: 6px;
  padding: 12px;
  text-align: center;
  font-size: 12px;
  color: #333;
  border: 1px solid #dee2e6;
}

.result-title, .rec-symbol, .perf-title, .param-title, .config-label {
  font-weight: 500;
  color: #666;
  margin-bottom: 4px;
  font-size: 11px;
}

.result-value, .rec-weight, .perf-accuracy, .param-value, .config-value {
  font-size: 14px;
  font-weight: 700;
  color: #333;
}

.rec-action {
  font-size: 11px;
  color: #666;
  margin-top: 2px;
}

.perf-details {
  margin-top: 8px;
}

.perf-details .perf-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 11px;
  color: #666;
  margin-bottom: 2px;
}

.perf-target {
  font-weight: 500;
  color: #333;
}

.perf-accuracy {
  font-weight: 600;
  color: #333;
}

.market-summary .summary-item, .optimized-params .param-card, .model-config .config-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #666;
  background: #e9ecef;
  border-radius: 6px;
  padding: 8px 12px;
  border: 1px solid #dee2e6;
}

.summary-label, .param-title, .config-label {
  font-weight: 500;
  color: #333;
}

.summary-value, .param-value, .config-value {
  font-weight: 600;
  color: #333;
}

/* 持仓历史 */
.history-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.history-select {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
}

.history-content {
  max-height: 400px;
  overflow-y: auto;
}

.history-day {
  border: 1px solid #eee;
  border-radius: 6px;
  margin-bottom: 12px;
  overflow: hidden;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  font-size: 14px;
  font-weight: 500;
}

.day-date {
  color: #333;
}

.day-value {
  font-weight: 600;
  color: #333;
}

.day-return {
  font-weight: 600;
}

.day-actions {
  padding: 12px 16px;
}

.action-item {
  display: flex;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 12px;
  align-items: center;
}

.action-item:last-child {
  border-bottom: none;
}

.action-item.buy {
  background: rgba(40, 167, 69, 0.1);
  margin: 4px 0;
  padding: 8px;
  border-radius: 4px;
}

.action-item.sell {
  background: rgba(220, 53, 69, 0.1);
  margin: 4px 0;
  padding: 8px;
  border-radius: 4px;
}

.action-item.system {
  background: rgba(108, 117, 125, 0.1);
  margin: 4px 0;
  padding: 8px;
  border-radius: 4px;
}

.action-symbol {
  font-weight: 600;
  color: #333;
  min-width: 60px;
}

.action-type {
  font-weight: 600;
  min-width: 60px;
}

.action-details {
  color: #666;
  flex: 1;
}

/* 控制区域 */
.control-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 颜色类 */
.positive {
  color: #28a745;
}

.negative {
  color: #dc3545;
}

   /* 响应式设计 */
  @media (max-width: 768px) {
    .info-grid {
      grid-template-columns: 1fr;
    }
    
    .advice-summary {
      grid-template-columns: 1fr;
    }
    
    .params-grid {
      grid-template-columns: repeat(2, 1fr);
    }
    
    .positions-header, .position-row {
      grid-template-columns: 1fr;
      gap: 4px;
    }
    
    .price, .value, .change, .action, .model-score, .optimization-score {
      text-align: left;
    }
    
    .live-actions {
      flex-direction: column;
    }
    
    .live-info {
      flex-direction: column;
      gap: 8px;
    }

    .results-grid, .recommendations-grid, .performance-grid, .summary-grid, .params-grid, .config-grid {
      grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
      gap: 8px;
    }
    
    .result-card, .recommendation-card, .performance-card, .param-card, .config-item {
      padding: 8px;
      font-size: 11px;
    }
    
    .result-value, .rec-weight, .perf-accuracy, .param-value, .config-value {
      font-size: 12px;
    }
  }
</style>
  